namespace ScrumSprintMonitor.Modules.BuildMonitor
{
	#region #using Directives

	using Extensibility;

	using Infrastructure;

	using Microsoft.Practices.Composite.Modularity;
	using Microsoft.Practices.Composite.Regions;
	using Microsoft.Practices.ServiceLocation;
	using Microsoft.Practices.Unity;

	using ViewModels;

	using IModule = Microsoft.Practices.Composite.Modularity.IModule;

	#endregion

	[Module(ModuleName = "Build Status")]
	public class BuildStatusModule : IModule
	{
        private readonly IUnityContainer container;
		private readonly ILogger<BuildStatusModule> logger;
		private readonly IRegionManager regionManager;
		private readonly IResourceManager resourceManager;
		private readonly IServiceLocator serviceLocator;

		public BuildStatusModule(IServiceLocator serviceLocator, IUnityContainer container, IRegionManager regionManager, IResourceManager resourceManager,
		                         ILogger<BuildStatusModule> logger)
		{
			this.serviceLocator = serviceLocator;
            this.container = container;
			this.regionManager = regionManager;
			this.resourceManager = resourceManager;
			this.logger = logger;

			this.logger.Info("Module starting...");
		}

		#region Implementation of IModule

		public void Initialize()
		{
			RegisterViewsAndServices();

			this.regionManager.RegisterViewWithRegion(RegionNames.PrimaryMonitorBackgroundRegion,
			                                          () => this.serviceLocator.GetInstance<IBuildStatusBackgroundViewModel>());
			this.regionManager.RegisterViewWithRegion(RegionNames.BuildStatusDetailsRegion,
			                                          () => this.serviceLocator.GetInstance<IBuildStatusDetailsViewModel>());
			this.regionManager.RegisterViewWithRegion(RegionNames.PrimaryMonitorBottomDockRegion,
			                                          () => this.serviceLocator.GetInstance<IFailedBuildRequesterViewModel>());
		}

		#endregion

		protected void RegisterViewsAndServices()
		{
			this.resourceManager.MergeDictionary(
			                                     "pack://application:,,,/ScrumSprintMonitor.Modules.BuildMonitor;component/DataTemplates/BuildStatusDataTemplate.xaml");
			this.resourceManager.MergeDictionary(
			                                     "pack://application:,,,/ScrumSprintMonitor.Modules.BuildMonitor;component/DataTemplates/FailedBuildRequesterDataTemplate.xaml");

		    this.container.RegisterType<IBuildStatusBackgroundViewModel, BuildStatusBackgroundViewModel>(new ContainerControlledLifetimeManager());
		    this.container.RegisterType<IBuildStatusDetailsViewModel, BuildStatusDetailsViewModel>(new ContainerControlledLifetimeManager());
		    this.container.RegisterType<IFailedBuildRequesterViewModel, FailedBuildRequesterViewModel>(new ContainerControlledLifetimeManager());
		}
	}
}